﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using LSQL;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using DocumentFormat.OpenXml.Bibliography;
using static DevExpress.Data.Filtering.Helpers.SubExprHelper.ThreadHoppingFiltering;

namespace Shopfloormanagement.Forms
{
	public partial class registerForm: DevExpress.XtraEditors.XtraForm
	{
        public static registerForm instance = new registerForm();
        public registerForm()
		{
            instance = this;
            InitializeComponent();
		}

		private void LoadFactory()
		{
            DataTable dtFac = SQL.ReturnDataTable3(SystemInfo.sys, "Factories", $"Del_tag = 0 and isONLINE = 1");
            publicFunc.ComboBoxInit(dtFac, cbFactory, "FactoryName", "ID");
		}

        private void registerForm_Load(object sender, EventArgs e)
        {
            LoadFactory();
            

        }
        private string GenerateSalt()
        {
            byte[] saltBytes = new byte[16];
            using (var rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(saltBytes);
            }
            return Convert.ToBase64String(saltBytes);
        }

        private string HashPassword(string password, string salt)
        {
            using (var sha256 = System.Security.Cryptography.SHA256.Create())
            {
                var saltedPassword = password + salt;
                var hashedBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(saltedPassword));
                return BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
            }
        }

        private void InsertUser()
        {
            if (txtName.Text == "")
            {
                XtraMessageBox.Show(LookAndFeel, "请输入名字");
                return;
            }
            if(txtLastname.Text == "")
            {
                XtraMessageBox.Show(LookAndFeel, "请输入姓氏");
                return;
            }
            if (txtEmail.Text == "")
            {
                XtraMessageBox.Show(LookAndFeel, "请输入邮箱");
                return;
            }
            if (txtPhone.Text == "")
            {
                XtraMessageBox.Show(LookAndFeel, "请输入电话");
                return;
            }
            if (txtLogin.Text == "")
            {
                XtraMessageBox.Show(LookAndFeel, "请输入登录账号");
                return;
            }
            if (txtPwd.Text == "")
            {
                XtraMessageBox.Show(LookAndFeel, "请输入密码");
                return;
            }
            DataTable dtLogin = SQL.ReturnDataTable3(SystemInfo.SQL, "Employees", $"LoginName = '{txtLogin.Text}' and Del_tag = 0");
            if (dtLogin.Rows.Count > 0)
            {
                XtraMessageBox.Show(LookAndFeel, "已有人注册此登录账号");
                return;
            }
            DataTable dtEmail = SQL.ReturnDataTable3(SystemInfo.SQL, "Employees", $"Email = '{txtEmail.Text}' and Del_tag = 0");
            if (dtLogin.Rows.Count > 0)
            {
                XtraMessageBox.Show(LookAndFeel, "已有人注册此邮箱");
                return;
            }

            string salt = GenerateSalt();
            string pwd = HashPassword(txtPwd.Text, salt);


            string FullName = txtName.Text + " " + txtLastname.Text;
            string col = "FirstName,LastName,Email,PhoneNumber,LoginName,PasswordHash,FactoryID,HomeDepartmentID,PasswordSalt,FullName";
            string value = $"'{txtName.Text}','{txtLastname.Text}','{txtEmail.Text}','{txtPhone.Text}','{txtLogin.Text}','{pwd}',{facID},{DepartmentID},'{salt}','{FullName}'";
            
            int res = SQL.InsertReturnID(SystemInfo.SQL, "Employees",col,value);
            if (res > 0)
            {
                string column = "EmployeeID,DepartmentID,StartDate,Scope";
                string value1 = $"{res},{DepartmentID},'{DateTime.Now.Date}',{scopeID}";
                int Relation = SQL.InsertReturnID(SystemInfo.SQL, "EmployeeDepartments", column, value1);
                if (Relation > 0)
                {
                    XtraMessageBox.Show(LookAndFeel, "注册成功！");
                    this.Close();
                }
                
            }
        }

        private int facID;
        private int DepartmentID;
        private int scopeID;
        private void cbScope_SelectedValueChanged(object sender, EventArgs e)
        {
            var selectedItem = cbScope.SelectedItem as publicFunc.ComboBoxItem;
            if (selectedItem != null)
            {
                var tag = selectedItem.Tag; // 这里可以使用tag
                scopeID = Convert.ToInt32(tag);
            }
        }
        private void cbDepartment_SelectedIndexChanged(object sender, EventArgs e)
        {
            var selectedItem = cbDepartment.SelectedItem as publicFunc.ComboBoxItem;
            if (selectedItem != null)
            {
                var tag = selectedItem.Tag; // 这里可以使用tag
                DepartmentID = Convert.ToInt32(tag);
            }
        }
        private void comboBoxEdit2_SelectedIndexChanged(object sender, EventArgs e)
        {
            var selectedItem = cbFactory.SelectedItem as publicFunc.ComboBoxItem;
            if (selectedItem != null)
            {
                var tag = selectedItem.Tag; // 这里可以使用tag
                facID = Convert.ToInt32(tag);
            }

            string regFac = Regex.Replace(cbFactory.Text, "[^a-zA-Z0-9\\s]", "");
            SystemInfo.UpdateSQLconnection(Login.instance.Addr, "SFM_" + regFac);

            DataTable dtDepartment = SQL.ReturnDataTable3(SystemInfo.SQL,"Departments",$"Del_tag = 0");
            publicFunc.ComboBoxInit(dtDepartment, cbDepartment, "DepartmentName", "ID");

            DataTable dtScope = SQL.ReturnDataTable3(SystemInfo.SQL, "Scope", $"Del_tag = 0 and ID != 4");
            publicFunc.ComboBoxInit(dtScope, cbScope, "Scope", "ID");
        }

        private void labelControl6_Click(object sender, EventArgs e)
        {

        }

        private void btnRegist_Click(object sender, EventArgs e)
        {
            if (txtPwd.Text != txtConfirm.Text)
            {
                XtraMessageBox.Show(LookAndFeel, "两次密码不同!");
                return;
            }
            InsertUser();
        }
    }
}